﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Threading;
using PersonalHealth.Data.IService;
using PersonalHealth.Data.Service;
using PersonalHealth.Data.Model;
using com.jwxcd.CommunityDriver;
using HealthManagement.Common;
using HealthManagement.Models;

namespace HealthManagement.Views
{
    /// <summary>
    /// BloodOximeter.xaml 的交互逻辑
    /// </summary>
    public partial class BloodOximeter : MeasureBase
    {
        MeasureUser user;
        IList<Threshold> thresholds;
        UserPanel parentPage;
        public BloodOximeter(MeasureUser user,UserPanel p)
        {
            InitializeComponent();
            this.user = user;
            this.parentPage = p;
            this.Loaded += new RoutedEventHandler(BloodOximeter_Loaded);
        }

        void BloodOximeter_Loaded(object sender, RoutedEventArgs e)
        {
            testStepGrid.Visibility = Visibility.Visible;

            Dispatcher.BeginInvoke(
                new Action(
                  () =>
                  {
                      connectTimer = new DispatcherTimer();
                      connectTimer.Interval = new TimeSpan(10000000);
                      connectTimer.Tick += new EventHandler(connectTimer_Tick);
                      connectSecondsCount = 0;
                      connectTimer.Start();
                  }
                )
            );
            driver.connect();
        }

       
        DispatcherTimer connectTimer;
        int connectSecondsCount = 0;
        void connectTimer_Tick(object sender, EventArgs e)
        {
            connectSecondsCount++;
            connectDown.Text = (30 - connectSecondsCount).ToString();
            if (connectSecondsCount == 30)
            {
                DispatcherTimer timer = sender as DispatcherTimer;
                timer.Stop();
                OnError("连接设备超时，请返回重试！");
            }
        }

       

        public override void onDriverConnected(object sender, EventArgs e)
        {
            Thread.Sleep(500);
            Dispatcher.Invoke(new Action(
               () =>
               {
                   if (connectTimer != null)
                       connectTimer.Stop();
                   testStepGrid.Visibility = Visibility.Collapsed;
                   resultStepGrid.Visibility = Visibility.Visible;

                   IUserService service = new UserService();
                   thresholds = service.GetThreshold("BO", user.Id);

                   oxyModel = new ChartModel(60);
                   oxyModel.AxisYMaxValue = 200;
                   oxyModel.AxisYMinValue = -100;
                   oxyModel.AxisYStep = 50;
                   // oxyModel.YIntercept = 100;
                   this.DataContext = oxyModel;
                   RadChart1.SamplingSettings.SamplingThreshold = oxyModel.SamplingThreshold;
               }));

        }

        ChartModel oxyModel;
        bool isStop = false;
        public override void onMeasure(object sender, MeasureEventArgs e)
        {
            if (!isStop)
            {
                Dispatcher.Invoke(new Action(
                       () =>
                       {
                           if (e.value.SpO2_value != 0 && e.value.Pulse != 0)
                           {
                               //血氧饱和度
                               SpO2.Text = e.value.SpO2_value.ToString();

                               //血氧脉率
                               Pulse.Text = e.value.Pulse.ToString();

                               foreach (var i in thresholds)
                               {
                                   if (i.MeasureSubType.Code == "SpO2")
                                   {
                                       if (e.value.SpO2_value < i.Min || e.value.SpO2_value > i.Max)
                                       {
                                           spO2Panel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ff8700")) as Brush;
                                       }
                                       else
                                       {
                                           spO2Panel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF6D9700")) as Brush;
                                       }
                                   }
                                   if (i.MeasureSubType.Code == "Pulse")
                                   {
                                       if (e.value.Pulse < i.Min || e.value.Pulse > i.Max)
                                       {
                                           pulsePanel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ff8700")) as Brush;
                                       }
                                       else
                                       {
                                           pulsePanel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF6D9700")) as Brush;
                                       }
                                   }
                               }
                           }


                           if (e.value.SpO2 == null)
                               return;

                           //如果全部为0直接return
                           bool isAllZero = true;
                           for (int i = 0; i < e.value.SpO2.Count; i++)
                           {
                               if (e.value.SpO2[i] != 0)
                               {
                                   isAllZero = false;
                                   break;
                               }
                           }
                           if (isAllZero)
                               return;

                           DateTime now = DateTime.Now;
                           oxyModel.EnqueueValue(e.value.SpO2, now);
                           oxyModel.SetUpAxisXRange(now);

                           oxyModel.Data = null;
                           oxyModel.Data = oxyModel.CpuData;
                           // RadChart1.ItemsSource = null;
                           // RadChart1.ItemsSource = oxyModel.Data;
                           //RadChart1.DefaultView.ChartArea.AxisY.MaxValue = oxyModel.AxisYMaxValue;
                           //RadChart1.DefaultView.ChartArea.AxisY.MinValue = oxyModel.AxisYMinValue;
                           //RadChart1.DefaultView.ChartArea.AxisY.Step = oxyModel.AxisYStep;
                           //RadChart1.ItemsSource = oxyModel.Data;
                           if (btnControl.Visibility != Visibility.Visible)
                               btnControl.Visibility = Visibility.Visible;


                       }
                    ));
            }
        }

        private void Control_Click(object sender, RoutedEventArgs e)
        {
            if (tbControl.Text == "停止")
            {
                oxyModel.Reset();
                isStop = true;

                tbControl.Text = "开始";
                Save.Visibility = Visibility.Visible;
                Cancel.Visibility = Visibility.Visible;
            }
            else if (tbControl.Text == "开始")
            {
                isStop = false;
                tbControl.Text = "停止";

                oxyModel.Data = null;
                Save.Visibility = Visibility.Collapsed;
                Cancel.Visibility = Visibility.Collapsed;
            }
        }

        //保存
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            save();
            //NavigationService.GoBack();
            parentPage.btnStop.IsEnabled = false;
            parentPage.contentBorder.Content = null;
        }

        //取消
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            //NavigationService.GoBack();
            parentPage.btnStop.IsEnabled = false;
            parentPage.contentBorder.Content = null;
        }

        private object lockObj = new object();
        private bool isUnload = false;
        public override void MeasureBase_Unloaded(object sender, RoutedEventArgs e)
        {
            lock (lockObj)
            {
                if (isUnload)
                {
                    return;
                }
                else
                {
                    if (connectTimer != null)
                        connectTimer.Stop();
                    base.MeasureBase_Unloaded(sender, e);
                    isUnload = true;

                }
            }

            
        }

        private void save()
        {
            int spO2, pulse;
            int.TryParse(SpO2.Text, out spO2);
            int.TryParse(Pulse.Text, out pulse);
            Measure_BO obj = new Measure_BO();
            obj.UserId = user.Id;
            obj.SpO2 = spO2;
            obj.Pulse = pulse;
            DateTime now = DateTime.Now;
            obj.MeasureTime = obj.CreateDate = obj.ModifyDate = now;

            IMeasure_BOService ser = new Measure_BOService();
            ser.Add(obj);
        }

    }
}
